/*
 * Copyright © 2010 LPRM Universidade Federal do Espírito Santo - RNP-GT CWTools
 * 
 * This file is part of GW-Android.
 * 
 * GW-Android is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * GW-Android is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GW-Android. If not, see <http://www.gnu.org/licenses/>.
 */
package br.ufes.cwtools.gw.android.components.image_picker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import br.ufes.cwtools.gw.android.components.Component;
import br.ufes.cwtools.gw.android.util.FileListing;

public class ImagePicker extends Component {
    private static final String LOG_TAG = "ImagePicker";

    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private static final int REQUEST_CODE_IMAGE_PICK = 2;

    private File temp = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.component_image_picker);

        this.temp = (File) getLastNonConfigurationInstance();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE:
                if (resultCode == RESULT_OK) {
                    Log.d(LOG_TAG, "IMAGE_CAPTURE result OK.");

                    // Já que a Motorola conseguiu bugar o aplicativo da câmera
                    // pra retornar uma foto pequena,
                    // preciso iterar sobre as últimas fotos e achar a mais
                    // recente. POG EXTREMO
                    if (temp == null) {
                        Log.w(LOG_TAG,
                                "Image capture result received, but no temp file found!");
                        return;
                    }

                    File latest = null;
                    File startingDirectory = new File("/sdcard/DCIM");
                    List<File> files = null;
                    try {
                        files = FileListing.getFileListing(startingDirectory);
                    } catch (FileNotFoundException e) {
                        Log.e(LOG_TAG,
                                "Erro na busca da imagem em alta definição.", e);
                    }

                    for (File file : files) {
                        if (file.isFile()
                                && (latest == null || latest.lastModified() < file
                                        .lastModified())) {
                            String absolutePath = file.getAbsolutePath();
                            if (!absolutePath.contains("thumb")) {
                                String fileName = file.getName().toLowerCase();
                                if (fileName.substring(fileName.length() - 4,
                                        fileName.length()).equals(".jpg")) {
                                    latest = file;
                                }
                            }
                        }
                    }

                    String sUri = latest.getAbsolutePath();

                    try {
                        sUri = MediaStore.Images.Media.insertImage(
                                this.getContentResolver(), sUri, null, null);
                    } catch (FileNotFoundException e) {
                        temp.delete();
                        temp = null;
                        return;
                    }

                    temp.delete();
                    temp = null;

                    getIntent().putExtra(EXTRA_ENTITY_URI, sUri); // Passa a
                                                                  // informação
                                                                  // para o
                                                                  // componente
                                                                  // seguinte.
                    selectNextComponentAndFinish("image_uri");
                } else {
                    Log.d(LOG_TAG, "IMAGE_CAPTURE result not OK.");
                }
                break;
            case REQUEST_CODE_IMAGE_PICK:
                if (resultCode == RESULT_OK) {
                    Log.d(LOG_TAG, "IMAGE_PICK_REQUEST result OK.");
                    Uri uri = data.getData();
                    String sUri = uri.toString();
                    getIntent().putExtra(EXTRA_ENTITY_URI, sUri);
                    Log.d(LOG_TAG, "EXTRA_IMAGE_URI: " + sUri);
                    selectNextComponentAndFinish("image_uri");
                } else {
                    Log.d(LOG_TAG, "IMAGE_PICK_REQUEST result not OK.");
                }
                break;
            default:
                Log.w(LOG_TAG, "Activity returned with unknown request code.");
                break;
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        return temp;
    }

    public void imageCaptureOnClick(View view) {
        Log.d(LOG_TAG, "Launching image capture activity.");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file;
        try {
            file = File.createTempFile("temp_file", "jpg");
        } catch (IOException e) {
            return;
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        this.temp = file;
        this.startActivityForResult(intent, REQUEST_CODE_IMAGE_CAPTURE);
        // TODO Tratar erro quando não existe uma activity para executar esta
        // ação;
        // duas opções: verificar previamente e desabilitar o botão ou capturar
        // a exceção no startActivity.
    }

    public void galleryOnClick(View view) {
        Log.d(LOG_TAG, "Launching image pick activity.");
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        this.startActivityForResult(intent, REQUEST_CODE_IMAGE_PICK);
        // TODO Tratar erro quando não existe uma activity para executar esta
        // ação.
    }
}
